package com.chhuang.huaao.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.chhuang.core.bean.QueryBean;
import com.chhuang.core.validation.ValidGroupSave;
import com.chhuang.core.validation.ValidGroupUpdate;
import com.chhuang.huaao.bean.HaCustomerQueryBean;
import com.chhuang.huaao.bean.HaFeedbackQueryBean;
import com.chhuang.huaao.bean.HaMachineQueryBean;
import com.chhuang.huaao.consts.HaConstact;
import com.chhuang.huaao.po.HaCustomer;
import com.chhuang.huaao.po.HaFeedback;
import com.chhuang.huaao.po.HaMachine;
import com.chhuang.huaao.service.IHaCustomerService;
import com.chhuang.huaao.service.IHaFeedbackService;
import com.chhuang.huaao.service.IHaMachineService;
import com.chhuang.huaao.thread.GeTuiThread;
import com.chhuang.huaao.thread.MachineAdminThread;
import com.chhuang.huaao.thread.MachineBinStallThread;
import com.chhuang.huaao.thread.MachineFlushTask;
import com.chhuang.huaao.thread.MachineRecoverThread;
import com.chhuang.huaao.thread.MachineStatusFlushThread;
import com.chhuang.huaao.thread.MachineTempTimeoutThread;
import com.chhuang.huaao.thread.MachineTimeIntervalThread;
import com.chhuang.huaao.thread.MachineTurnOnThread;
import com.chhuang.huaao.thread.TokenFileThread;
import com.chhuang.huaao.util.BaiduGeocoderUtil;
import com.chhuang.huaao.vo.UserVo;
import com.chhuang.system.consts.SysConstants;
import com.chhuang.system.po.ChUser;
import com.chhuang.system.service.IChUserService;
import com.chhuang.utils.Assert;
import com.chhuang.utils.config.SysConfig;
import com.chhuang.utils.file.FileUtil;
import com.chhuang.utils.string.Md5Util;

@Controller
@RequestMapping("/admin/api")
public class AdminController {
	private static final Log log = LogFactory.getLog(AdminController.class);
	
	@Autowired
	private IHaCustomerService haCustomerService;
	@Autowired
	private IHaMachineService haMachineService;
	@Autowired
	private IChUserService chUserService;
	@Autowired
	private IHaFeedbackService haFeedbackService;
	
	/**
	 * 登录校验令牌
	 */
	public static Map<String, JSONObject> tokens = new Hashtable<String, JSONObject>();
	
	static{
		File file = new File(SysConfig.getValue(SysConstants.Config.ADMIN_TOKEN_PATH));
		if(file.exists()){
			try {
				FileInputStream freader = new FileInputStream(file);
				ObjectInputStream input = new ObjectInputStream(freader);
				tokens = (Map<String, JSONObject>) input.readObject();
				input.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 管理员手机app登录
	 * @param customerAccount
	 * @param customerPassword
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/login.app",method=RequestMethod.POST)
	@ResponseBody
	public Object login(String username, String password) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(username) && Assert.isValidString(password)){
			List<ChUser> users = chUserService.findByUsername(username);
			String pwd = Md5Util.md5(password, username);
			if(Assert.isValidCollection(users) && users.get(0)!=null && pwd.equals(users.get(0).getPassword())){
				ChUser user = users.get(0);
				if(user.getLocked()==null || !user.getLocked()){
					json.put(SysConstants.Status.SUCCESS, true);
					ChUser temp = (ChUser) BeanUtils.cloneBean(user);
					temp.setPassword(null);
					json.put(SysConstants.Status.RESULT, temp);
					
					String token = UUID.randomUUID().toString().replaceAll("-", "");
					json.put(SysConstants.Token.TOKEN, token);
					JSONObject tokenObj = new JSONObject();
					tokenObj.put(SysConstants.Token.TOKEN, token);
					tokenObj.put(SysConstants.Token.TIME, System.currentTimeMillis());
					tokens.put(user.getUserId(), tokenObj);
					//把token写入文件
					new Thread(new TokenFileThread(tokens, SysConfig.getValue(SysConstants.Config.ADMIN_TOKEN_PATH))).start();
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "用户账号被锁定，无法使用");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "账号或密码不正确");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "账号密码不为空");
		}
		
		return json;
	}
	

	/**
	 * 查询用户信息
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/findUser.app",method=RequestMethod.POST)
	@ResponseBody
	public Object findUser(String userId) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(userId)){
			ChUser user = chUserService.findByPrimaryKey(userId);
			if(user!=null){
				if(user.getLocked()==null || !user.getLocked()){
					json.put(SysConstants.Status.SUCCESS, true);
					ChUser temp = (ChUser) BeanUtils.cloneBean(user);
					temp.setPassword(null);
					json.put(SysConstants.Status.RESULT, temp);
					JSONObject tokenObj = tokens.get(userId);
					if(tokenObj!=null){
						String token = tokenObj.getString(SysConstants.Token.TOKEN);
						if(Assert.isValidString(token))
							json.put(SysConstants.Token.TOKEN, token);
					}
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "用户账号被锁定，无法使用");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "用户不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "用户ID不为空");
		}
		
		return json;
	}
	
	/**
	 * 修改个人信息
	 * @param user
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/editUserinfo.app",method=RequestMethod.POST)
	@ResponseBody
	public Object editUserinfo(UserVo user, HttpServletRequest request) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(user.getUserId())){
			ChUser chUser = chUserService.findByPrimaryKey(user.getUserId());
			if(chUser!=null){
				if(user.getLocked()==null || !user.getLocked()){
					String filePath = null, oldPhoto = null;
					chUser.setNickname(user.getNickname());
					chUser.setPhone(user.getPhone());
					chUser.setEmail(user.getEmail());
					MultipartFile mfile = user.getFile();
					if(mfile!=null && !mfile.isEmpty()){
						//文件保存路径 
						filePath = request.getSession().getServletContext().getRealPath("/");
						//文件原名
						String originalFilename = mfile.getOriginalFilename();
						//文件名
		                String filename = "Resource/"+UUID.randomUUID()+originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
		                File file = new File(filePath+filename);
		                FileUtil.makeFilePath(file);
		                //转存文件 
		                mfile.transferTo(file);
		                oldPhoto = chUser.getUserphoto();
		                chUser.setUserphoto(filename);
					}
					if(chUserService.update(chUser)>0){
						json.put(SysConstants.USER_ID, chUser.getUserId());
						json.put(SysConstants.Status.SUCCESS, true);
					}else{
						json.put(SysConstants.Status.SUCCESS, false);
						json.put(SysConstants.Status.RESULT, "修改个人信息失败");
					}
					if(Assert.isValidString(oldPhoto)){
						FileUtils.deleteQuietly(new File(filePath+oldPhoto));
					}
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "用户账号被锁定，无法使用");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "用户不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "用户ID不为空");
		}
		
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 修改密码
	 * @param userId
	 * @param oldPassword
	 * @param password
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/updatePassword.app",method=RequestMethod.POST)
	@ResponseBody
	public Object updatePassword(String userId, String oldPassword, String password) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(userId) && Assert.isValidString(oldPassword) && Assert.isValidString(password)){
			ChUser user = chUserService.findByPrimaryKey(userId);
			if(user!=null){
				if(user.getLocked()==null || !user.getLocked()){
					oldPassword = Md5Util.md5(oldPassword, user.getUsername());
					if(oldPassword.equals(user.getPassword())){
						user.setPassword(Md5Util.md5(password, user.getUsername()));
						if(chUserService.update(user)>0){
							json.put(SysConstants.Status.SUCCESS, true);
						}else{
							json.put(SysConstants.Status.SUCCESS, false);
							json.put(SysConstants.Status.RESULT, "修改密码失败");
						}
					}else{
						json.put(SysConstants.Status.SUCCESS, false);
						json.put(SysConstants.Status.RESULT, "原密码不正确");
					}
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "用户账号被锁定，无法使用");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "用户不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "用户ID或密码不为空");
		}
		
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 根据客户id获取客户信息
	 * @param customerId
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/findCustomerById.app",method=RequestMethod.POST)
	@ResponseBody
	public Object findCustomerById(String customerId) throws Exception{
		JSONObject json = new JSONObject();
		
		log.debug("客户ID："+customerId);
		if(Assert.isValidString(customerId)){
			HaCustomer customer = haCustomerService.findByPrimaryKey(customerId);
			if(customer!=null){
				json.put(SysConstants.Status.SUCCESS, true);
				json.put(SysConstants.Status.RESULT, customer);
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "客户不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "客户ID不为空");
		}
		
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 获取客户列表
	 * @param customerQueryBean
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/getCustomerList.app",method=RequestMethod.POST)
	@ResponseBody
	public Object getCustomerList(@RequestBody HaCustomerQueryBean customerQueryBean) throws Exception{
		log.debug(customerQueryBean.getPageSize()+";"+customerQueryBean.getPageNum()
				+";"+customerQueryBean.getOrderBy()+";"+customerQueryBean.isDesc()
				+";"+customerQueryBean.isOr());
		
		QueryBean<HaCustomer> queryBean = haCustomerService.seniorQuery(customerQueryBean);
		
		return queryBean;
	}
	
	/**
	 * 添加客户信息
	 * @param customer
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/saveCustomer.app",method=RequestMethod.POST)
	@ResponseBody
	public Object saveCustomer(@RequestBody @Validated(value={ValidGroupSave.class}) HaCustomer customer, BindingResult bindingResult) throws Exception{
		JSONObject json = new JSONObject();
		if(bindingResult.hasErrors()){
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, bindingResult.getAllErrors().get(0).getDefaultMessage());
			log.debug(json.toString());
			return json;
		}
		if(haCustomerService.findByCustomerAccount(customer.getCustomerAccount())==null){
			customer.setCustomerPassword(Md5Util.md5(customer.getCustomerAccount(), customer.getCustomerAccount()));
			customer.setLocked(false);
			Date now = new Date();
			customer.setCreateTime(now);
			customer.setModifyTime(now);
			if(haCustomerService.save(customer)>0){
				json.put(HaConstact.CUSTOMER_ID, customer.getCustomerId());
				json.put(SysConstants.Status.SUCCESS, true);
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "保存客户信息失败");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "客户账号已存在");
		}
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 修改客户信息
	 * @param customer
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/editCustomer.app",method=RequestMethod.POST)
	@ResponseBody
	public Object editCustomer(@RequestBody @Validated(value={ValidGroupUpdate.class}) HaCustomer customer, BindingResult bindingResult) throws Exception{
		JSONObject json = new JSONObject();
		if(bindingResult.hasErrors()){
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, bindingResult.getAllErrors().get(0).getDefaultMessage());
			log.debug(json.toString());
			return json;
		}
		if(Assert.isValidString(customer.getCustomerId())){
			HaCustomer customerTemp = haCustomerService.findByPrimaryKey(customer.getCustomerId());
			if(customerTemp!=null){
				Date now = new Date();
				customerTemp.setModifyTime(now);
				customerTemp.setCustomerGender(customer.getCustomerGender());
				customerTemp.setCustomerName(customer.getCustomerName());
				customerTemp.setCustomerCompany(customer.getCustomerCompany());
				if(haCustomerService.update(customerTemp)>0){
					json.put(HaConstact.CUSTOMER_ID, customerTemp.getCustomerId());
					json.put(SysConstants.Status.SUCCESS, true);
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "修改客户信息失败");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "客户账号不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "客户ID不为空");
		}
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 删除客户信息
	 * @param ids
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/delCustomers/{ids}.app",method=RequestMethod.DELETE)
	@ResponseBody
	public Object delCustomers(@PathVariable String ids, HttpServletRequest request) throws Exception{
		JSONObject json = new JSONObject();
		if(Assert.isValidString(ids)){
			String[] customerIds = ids.split(SysConstants.Symbol.COMMA);
			for(String id : customerIds){
				HaCustomer temp = haCustomerService.findByPrimaryKey(id);
				String photo = temp.getCustomerPhoto();
				if(haCustomerService.deleteByPrimaryKey(id)>0){
					if(Assert.isValidString(photo)){
						//文件保存路径 
						String filePath = request.getSession().getServletContext().getRealPath("/");
						FileUtils.deleteQuietly(new File(filePath+photo));
					}
					haMachineService.updateNullMachineCustomerIds(id);
				}
			}
			json.put(SysConstants.Status.SUCCESS, true);
		}
		log.debug(ids+":::"+json.toString());
		return json;
	}
	
	/**
	 * 重置密码
	 * @param ids
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/resetCustomerPassword.app",method=RequestMethod.POST)
	@ResponseBody
	public Object resetCustomerPassword(String ids) throws Exception{
		JSONObject json = new JSONObject();
		if(Assert.isValidString(ids)){
			String[] customerIds = ids.split(SysConstants.Symbol.COMMA);
			for(String customerId : customerIds){
				HaCustomer customer = haCustomerService.findByPrimaryKey(customerId);
				if(customer != null){
					customer.setCustomerPassword(Md5Util.md5(customer.getCustomerAccount(), customer.getCustomerAccount()));
					customer.setModifyTime(new Date());
					haCustomerService.update(customer);
				}
			}
			json.put(SysConstants.Status.SUCCESS, true);
		}
		return json;
	}
	
	/**
	 * 锁定/解锁
	 * @param ids
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/lockedCustomer.app",method=RequestMethod.POST)
	@ResponseBody
	public Object lockedCustomer(String ids) throws Exception{
		JSONObject json = new JSONObject();
		if(Assert.isValidString(ids)){
			String[] customerIds = ids.split(SysConstants.Symbol.COMMA);
			for(String customerId : customerIds){
				HaCustomer customer = haCustomerService.findByPrimaryKey(customerId);
				if(customer != null){
					customer.setLocked(customer.getLocked()==null || !customer.getLocked());
					customer.setModifyTime(new Date());
					haCustomerService.update(customer);
				}
			}
			json.put(SysConstants.Status.SUCCESS, true);
		}
		return json;
	}
	
	/**
	 * 根据客户id获取设备的设备信息
	 * @param machineId
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/findMachinesByCustomerId.app",method=RequestMethod.POST)
	@ResponseBody
	public Object findMachinesByCustomerId(String customerId) throws Exception{
		JSONObject json = new JSONObject();
		log.debug("客户ID："+customerId);
		
		if(Assert.isValidString(customerId)){
			List<HaMachine> machines = haMachineService.findMachinesByCustomerId(customerId);
			json.put(SysConstants.Status.SUCCESS, true);
			json.put(SysConstants.Status.RESULT, machines);
//			new Thread(new MachineFlushTask(machines)).start();
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "客户ID不为空");
		}
		
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 根据设备id获取设备信息
	 * @param machineId
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/findMachineById.app",method=RequestMethod.POST)
	@ResponseBody
	public Object findMachineById(String machineId) throws Exception{
		JSONObject json = new JSONObject();
		log.debug("设备ID："+machineId);
		
		if(Assert.isValidString(machineId)){
			HaMachine machine = haMachineService.findByPrimaryKey(machineId);
			if(machine!=null){
				json.put(SysConstants.Status.SUCCESS, true);
				json.put(SysConstants.Status.RESULT, machine);
				if(Assert.isValidString(machine.getCustomerId())){
					HaCustomer c = haCustomerService.findByPrimaryKey(machine.getCustomerId());
					if(c!=null){
						json.put(c.getCustomerId(), c);
					}
				}
				if(Assert.isValidString(machine.getCustomerId1())){
					HaCustomer c = haCustomerService.findByPrimaryKey(machine.getCustomerId1());
					if(c!=null){
						json.put(c.getCustomerId(), c);
					}
				}
				if(Assert.isValidString(machine.getCustomerId2())){
					HaCustomer c = haCustomerService.findByPrimaryKey(machine.getCustomerId2());
					if(c!=null){
						json.put(c.getCustomerId(), c);
					}
				}
				if(Assert.isValidString(machine.getCustomerId3())){
					HaCustomer c = haCustomerService.findByPrimaryKey(machine.getCustomerId3());
					if(c!=null){
						json.put(c.getCustomerId(), c);
					}
				}
				
				if(machine.getMachineOnlineStatus()!=null && machine.getMachineOnlineStatus()==1){
					//启动线程命令设备刷新设备信息
					new Thread(new MachineStatusFlushThread(machine)).start();
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "设备不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "设备ID不为空");
		}
		
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 获取设备列表
	 * @param machineQueryBean
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/getMachineList.app",method=RequestMethod.POST)
	@ResponseBody
	public Object getMachineList(@RequestBody HaMachineQueryBean machineQueryBean) throws Exception{
		log.debug(machineQueryBean.getPageSize()+";"+machineQueryBean.getPageNum()
				+";"+machineQueryBean.getOrderBy()+";"+machineQueryBean.isDesc()
				+";"+machineQueryBean.isOr());
		
		QueryBean<HaMachine> queryBean = haMachineService.seniorQuery(machineQueryBean);
//		new Thread(new MachineFlushTask(queryBean.getResult())).start();
		
		return queryBean;
	}
	
	/**
	 * 添加设备信息
	 * @param machine
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/saveMachine.app",method=RequestMethod.POST)
	@ResponseBody
	public Object saveMachine(@RequestBody @Validated(value={ValidGroupSave.class}) HaMachine machine, BindingResult bindingResult) throws Exception{
		JSONObject json = new JSONObject();
		if(bindingResult.hasErrors()){
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, bindingResult.getAllErrors().get(0).getDefaultMessage());
			log.debug(json.toString());
			return json;
		}
		if(haMachineService.findMachineByMachineNum(machine.getMachineNum())==null){
			Date now = new Date();
			machine.setCreateTime(now);
			machine.setModifyTime(now);
			machine.setCustomerId(newOrfindCustomer(machine.getCustomerId()));
			machine.setCustomerId1(newOrfindCustomer(machine.getCustomerId1()));
			machine.setCustomerId2(newOrfindCustomer(machine.getCustomerId2()));
			machine.setCustomerId3(newOrfindCustomer(machine.getCustomerId3()));
			if(haMachineService.save(machine)>0){
				json.put(HaConstact.MACHINE_ID, machine.getMachineId());
				json.put(SysConstants.Status.SUCCESS, true);
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "保存设备信息失败");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "设备已存在");
		}
		log.debug(json.toString());
		return json;
	}

	/**
	 * 修改设备信息
	 * @param machine
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/editMachine.app",method=RequestMethod.POST)
	@ResponseBody
	public Object editMachine(@RequestBody @Validated(value={ValidGroupUpdate.class}) HaMachine machine, BindingResult bindingResult) throws Exception{
		JSONObject json = new JSONObject();
		if(bindingResult.hasErrors()){
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, bindingResult.getAllErrors().get(0).getDefaultMessage());
			log.debug(json.toString());
			return json;
		}
		if(Assert.isValidString(machine.getMachineId())){
			HaMachine machineTemp = haMachineService.findByPrimaryKey(machine.getMachineId());
			if(machineTemp!=null){
				Date now = new Date();
				machineTemp.setModifyTime(now);
				machineTemp.setMachineNum(machine.getMachineNum());
				machineTemp.setMachineAname(machine.getMachineAname());
				
				machineTemp.setCustomerId(newOrfindCustomer(machine.getCustomerId()));
				machineTemp.setCustomerId1(newOrfindCustomer(machine.getCustomerId1()));
				machineTemp.setCustomerId2(newOrfindCustomer(machine.getCustomerId2()));
				machineTemp.setCustomerId3(newOrfindCustomer(machine.getCustomerId3()));
				
				if(haMachineService.update(machineTemp)>0){
					json.put(HaConstact.MACHINE_ID, machineTemp.getMachineId());
					json.put(SysConstants.Status.SUCCESS, true);
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "修改设备信息失败");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "设备不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "设备ID不为空");
		}
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 新建客户
	 * @param phone
	 * @return
	 * @throws Exception 
	 */
	private String newOrfindCustomer(String phone) throws Exception{
		if(Assert.isInvalidString(phone)){
			return null;
		}
		HaCustomer customerTemp = haCustomerService.findByCustomerAccount(phone);
		if(customerTemp==null){
			customerTemp = new HaCustomer();
			customerTemp.setCustomerAccount(phone);
			customerTemp.setCustomerPhone(phone);
			customerTemp.setCustomerPassword(Md5Util.md5(phone, phone));
			Date now = new Date();
			customerTemp.setCreateTime(now);
			customerTemp.setModifyTime(now);
			haCustomerService.save(customerTemp);
		}
		return customerTemp.getCustomerId();
	}
	
	/**
	 * 删除设备信息
	 * @param ids
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/delMachines/{ids}.app",method=RequestMethod.DELETE)
	@ResponseBody
	public Object delMachines(@PathVariable String ids) throws Exception{
		JSONObject json = new JSONObject();
		if(Assert.isValidString(ids)){
			String[] machineIds = ids.split(SysConstants.Symbol.COMMA);
			if(Assert.isValidArray(machineIds)){
				List<String> machineIdList = Arrays.asList(machineIds);
				haMachineService.deleteByPrimaryKeys(machineIdList);
				json.put(SysConstants.Status.SUCCESS, true);
			}
		}
		log.debug(ids+":::"+json.toString());
		return json;
	}
	
	/**
	 * 校验用户名密码
	 * @param userId
	 * @param password
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/checkPassword.app",method=RequestMethod.POST)
	@ResponseBody
	public Object checkPassword(String userId, String password) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(userId) && Assert.isValidString(password)){
			ChUser user = chUserService.findByPrimaryKey(userId);
			if(user!=null){
				log.debug("锁定："+user.getLocked());
				if(user.getLocked()==null || !user.getLocked()){
					password = Md5Util.md5(password, user.getUsername());
					if(password.equals(user.getPassword())){
						json.put(SysConstants.Status.SUCCESS, true);
					}else{
						json.put(SysConstants.Status.SUCCESS, false);
						json.put(SysConstants.Status.RESULT, "密码不正确");
					}
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "用户账号被锁定，无法使用");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "用户不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "用户ID和密码不为空");
		}
		
		return json;
	}
	
	/**
	 * 修改温度与时间参数
	 * @param machine
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/editMachineTempTimeout.app",method=RequestMethod.POST)
	@ResponseBody
	public Object editMachineTempTimeout(@RequestBody HaMachine machine) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(machine.getMachineId())){
			HaMachine machineTemp = haMachineService.findByPrimaryKey(machine.getMachineId());
			if(machineTemp!=null){
				if(machineTemp.getMachineOnlineStatus()!=null && machineTemp.getMachineOnlineStatus()==1){
					Date now = new Date();
					machineTemp.setModifyTime(now);
//					machine.getCustomerId(); //userId保存在这里了
					machineTemp.setMachineTurnOffFireTemp(machine.getMachineTurnOffFireTemp());
					machineTemp.setMachineTurnOffPumpTemp(machine.getMachineTurnOffPumpTemp());
					machineTemp.setMachineTurnOnFireTemp(machine.getMachineTurnOnFireTemp());
					machineTemp.setMachineTurnOnPumpTemp(machine.getMachineTurnOnPumpTemp());
					machineTemp.setMachineTurnSmokeTemp(machine.getMachineTurnSmokeTemp());
					
					machineTemp.setMachineTurnOffBlowerTimeout(machine.getMachineTurnOffBlowerTimeout());
					machineTemp.setMachineTurnOffWindTimeout(machine.getMachineTurnOffWindTimeout());
					machineTemp.setMachineTurnOnPreFeedTimeout(machine.getMachineTurnOnPreFeedTimeout());
					machineTemp.setMachineTurnOnTimeout(machine.getMachineTurnOnTimeout());
					
					if(haMachineService.update(machineTemp)>0){
						json.put(HaConstact.MACHINE_ID, machineTemp.getMachineId());
						json.put(SysConstants.Status.SUCCESS, true);
						//发送修改温度与时间参数命令
						new Thread(new MachineTempTimeoutThread()).start();
					}else{
						json.put(SysConstants.Status.SUCCESS, false);
						json.put(SysConstants.Status.RESULT, "修改温度与时间参数失败");
					}
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "设备离线");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "设备不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "设备ID不为空");
		}
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 修改时间段控制参数
	 * @param machine
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/editMachineTimeInterval.app",method=RequestMethod.POST)
	@ResponseBody
	public Object editMachineTimeInterval(@RequestBody HaMachine machine) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(machine.getMachineId())){
			HaMachine machineTemp = haMachineService.findByPrimaryKey(machine.getMachineId());
			if(machineTemp!=null){
				if(machineTemp.getMachineOnlineStatus()!=null && machineTemp.getMachineOnlineStatus()==1){
					Date now = new Date();
					machineTemp.setModifyTime(now);
//					machine.getCustomerId(); //userId保存在这里了
					machineTemp.setMachineWorkTimeInterval1(machine.getMachineWorkTimeInterval1());
					machineTemp.setMachineWorkTimeInterval2(machine.getMachineWorkTimeInterval2());
					machineTemp.setMachineWorkTimeInterval3(machine.getMachineWorkTimeInterval3());
					machineTemp.setMachineWorkTimeInterval4(machine.getMachineWorkTimeInterval4());
					machineTemp.setMachineWorkTimeInterval5(machine.getMachineWorkTimeInterval5());
					machineTemp.setMachineWorkTimeInterval6(machine.getMachineWorkTimeInterval6());
					machineTemp.setMachineWorkTimeInterval7(machine.getMachineWorkTimeInterval7());
					machineTemp.setMachineWorkTimeInterval8(machine.getMachineWorkTimeInterval8());
					
					if(haMachineService.update(machineTemp)>0){
						json.put(HaConstact.MACHINE_ID, machineTemp.getMachineId());
						json.put(SysConstants.Status.SUCCESS, true);
						//发送修改时间段控制参数命令
						new Thread(new MachineTimeIntervalThread()).start();
					}else{
						json.put(SysConstants.Status.SUCCESS, false);
						json.put(SysConstants.Status.RESULT, "修改时间段控制参数失败");
					}
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "设备离线");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "设备不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "设备ID不为空");
		}
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 开机或关机
	 * @param customerId
	 * @param machineId
	 * @param turnOn
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/turnOnMachine.app",method=RequestMethod.POST)
	@ResponseBody
	public Object turnOnMachine(String machineId, String userId, Boolean turnOn) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(machineId) && turnOn!=null){
			HaMachine machine = haMachineService.findByPrimaryKey(machineId);
			if(machine!=null){
				if(machine.getMachineOnlineStatus()!=null && machine.getMachineOnlineStatus()==1){
					json.put(SysConstants.Status.SUCCESS, true);
					//发送开机、关机命令
					new Thread(new MachineTurnOnThread(machine, userId, turnOn)).start();
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "设备离线");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "设备不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "设备ID不为空");
		}
		
		return json;
	}
	
	/**
	 * 修改料机档位
	 * @param customerId
	 * @param machineId
	 * @param binStall
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/editMachineBinStall.app",method=RequestMethod.POST)
	@ResponseBody
	public Object editMachineBinStall(String machineId, String userId, Integer binStall) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(machineId) && binStall!=null){
			HaMachine machine = haMachineService.findByPrimaryKey(machineId);
			if(machine!=null){
				if(machine.getMachineOnlineStatus()!=null && machine.getMachineOnlineStatus()==1){
					Date now = new Date();
					machine.setModifyTime(now);
					machine.setMachineBinStall(binStall);
					if(haMachineService.update(machine)>0){
						json.put(SysConstants.Status.SUCCESS, true);
						//发送修改料机档位命令
						new Thread(new MachineBinStallThread()).start();
					}else{
						json.put(SysConstants.Status.SUCCESS, false);
						json.put(SysConstants.Status.RESULT, "修改料机档位失败");
					}
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "设备离线");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "设备不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "设备ID不为空");
		}
		
		return json;
	}
	
	/**
	 * 恢复出厂设置
	 * @param customerId
	 * @param machineId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/recoverMachine.app",method=RequestMethod.POST)
	@ResponseBody
	public Object recoverMachine(String machineId, String userId) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(machineId)){
			HaMachine machine = haMachineService.findByPrimaryKey(machineId);
			if(machine!=null){
				if(machine.getMachineOnlineStatus()!=null && machine.getMachineOnlineStatus()==1){
					json.put(SysConstants.Status.SUCCESS, true);
					//发送恢复出厂设置命令，恢复出厂设置后，需要返回一份最新的设备信息
					new Thread(new MachineRecoverThread()).start();
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "设备离线");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "设备不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "设备ID不为空");
		}
		
		return json;
	}
	
	/**
	 * 管理员修改使用期限
	 * @param machineId
	 * @param date
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/editMachineDeadline.app",method=RequestMethod.POST)
	@ResponseBody
	public Object editMachineDeadline(String machineId, String userId, Date date) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(machineId)){
			HaMachine machine = haMachineService.findByPrimaryKey(machineId);
			if(machine!=null){
				if(machine.getMachineOnlineStatus()!=null && machine.getMachineOnlineStatus()==1){
					Date now = new Date();
					machine.setModifyTime(now);
					machine.setMachineAdminDeadline(date);
					if(haMachineService.update(machine)>0){
						json.put(SysConstants.Status.SUCCESS, true);
						//发送管理员修改使用期限命令
						new Thread(new MachineAdminThread()).start();
					}else{
						json.put(SysConstants.Status.SUCCESS, false);
						json.put(SysConstants.Status.RESULT, "修改料机档位失败");
					}
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "设备离线");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "设备不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "设备ID不为空");
		}
		
		return json;
	}
	
	/**
	 * 获取反馈列表
	 * @param feedbackQueryBean
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/getFeedbackList.app",method=RequestMethod.POST)
	@ResponseBody
	public Object getList(@RequestBody HaFeedbackQueryBean feedbackQueryBean) throws Exception{
		log.debug(feedbackQueryBean.getPageSize()+";"+feedbackQueryBean.getPageNum()
				+";"+feedbackQueryBean.getOrderBy()+";"+feedbackQueryBean.isDesc()
				+";"+feedbackQueryBean.isOr());
		
		QueryBean<HaFeedback> queryBean = haFeedbackService.seniorQuery(feedbackQueryBean);
		
		return queryBean;
	}
	
	/**
	 * 删除反馈信息
	 * @param ids
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/delFeedbacks/{ids}.app",method=RequestMethod.DELETE)
	@ResponseBody
	public Object delFeedbacks(@PathVariable String ids) throws Exception{
		JSONObject json = new JSONObject();
		if(Assert.isValidString(ids)){
			String[] feedbackIds = ids.split(SysConstants.Symbol.COMMA);
			if(Assert.isValidArray(feedbackIds)){
				List<String> list = Arrays.asList(feedbackIds);
				haFeedbackService.deleteByPrimaryKeys(list);
				json.put(SysConstants.Status.SUCCESS, true);
			}
			json.put(SysConstants.Status.SUCCESS, true);
		}
		log.debug(ids+":::"+json.toString());
		return json;
	}
	
	/**
	 * 推送消息
	 * @param customerId
	 * @param title
	 * @param content
	 * @param payload
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/pushMessage.app",method=RequestMethod.POST)
	@ResponseBody
	public Object pushMessage(String customerId, String title, String content, String payload) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(customerId) && Assert.isValidString(title) && Assert.isValidString(content)){
			HaCustomer customer = haCustomerService.findByPrimaryKey(customerId);
			if(customer != null && Assert.isValidString(customer.getClientId())){
				JSONObject message = new JSONObject();
				message.put("title", title);
				message.put("content", content);
				if(Assert.isValidString(payload)){
					message.put("payload", payload);
				}else{
					message.put("payload", "");
				}
				new Thread(new GeTuiThread(customer.getClientId(), message)).start();
				json.put(SysConstants.Status.SUCCESS, true);
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "客户账号不存在或者还不支持推送");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "主要参数不为空");
		}
		
		return json;
	}
	
	/**
	 * 逆向地理解析
	 * @param location
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/reGeocoder.app",method=RequestMethod.POST)
	@ResponseBody
	public Object removeMachine(String location) throws Exception{
		return JSONObject.parse(BaiduGeocoderUtil.reGeocoder(location));
	}
	
	/**
	 * 返回重新登录
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/relogin.app",method={RequestMethod.GET,RequestMethod.POST,RequestMethod.DELETE,RequestMethod.PUT})
	@ResponseBody
	public Object relogin() throws Exception{
		JSONObject json = new JSONObject();
		json.put(SysConstants.Status.SUCCESS, false);
		json.put(SysConstants.Status.RESULT, "relogin");
		return json;
	}
}
